import request from '@/utils/request'

/**
 * 下载导入模板
 * @param {string} templateUrl 模板下载地址
 * @param {string} fileName 文件名
 * @returns {Promise}
 */
export function downloadTemplate(templateUrl, fileName = '导入模板.xlsx') {
  return request({
    url: templateUrl,
    method: 'post',
    responseType: 'blob'
  }).then(response => {
    // 创建Blob对象进行下载
    const blob = new Blob([response], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const downloadElement = document.createElement('a')
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = fileName
    document.body.appendChild(downloadElement)
    downloadElement.click()
    document.body.removeChild(downloadElement)
    window.URL.revokeObjectURL(href)
    return Promise.resolve()
  }).catch(error => {
    console.error('下载模板失败:', error)
    return Promise.reject(error)
  })
}

/**
 * 处理导入结果
 * @param {Object} result 导入结果
 * @param {Function} successCallback 成功回调
 * @param {Function} errorCallback 失败回调
 */
export function handleImportResult(result, successCallback, errorCallback) {
  if (result.response && result.response.code === 200) {
    this.$modal.msgSuccess(result.message || '导入成功')
    if (successCallback) {
      successCallback(result)
    }
  } else {
    this.$modal.msgError(result.message || '导入失败')
    if (errorCallback) {
      errorCallback(result)
    }
  }
}

export default {
  downloadTemplate,
  handleImportResult
}
